package com.rzico.sbl.ui.report.dispatch

import android.widget.TextView
import androidx.lifecycle.MutableLiveData
import com.google.gson.Gson
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lzg.extend.jackson.JsonUtil
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityReportDispatchSecondBinding
import com.rzico.sbl.model.DispatchPay
import com.rzico.sbl.ui.report.other.goToDispatchThird
import com.rzico.sbl.viewmodel.ReportDispatchViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.helper.doubleValue
import com.xinnuo.common.helper.intValue
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.slimadapter.SlimAdapter
import org.json.JSONArray
import org.json.JSONObject

class ReportDispatchSecondActivity : BaseActivity(R.layout.activity_report_dispatch_second) {

    private val mBinding by lazy { ActivityReportDispatchSecondBinding.bind(getRootView()) }

    private lateinit var mTotalView: TextView
    private lateinit var mShipId: String
    private lateinit var mOrderSn: String
    private lateinit var mShippingSn: String
    private val mTotalEvent = MutableLiveData(mList.size)

    override fun getViewModel() = get<ReportDispatchViewModel>()

    override fun initData() {
        initTitle(title = "收款")

        initLayout()
        observeTotal()

        getData()
    }

    private fun initLayout() {
        mBinding.listLayout.apply {
            swipeRefresh.isEnabled = false

            recycleList.also { layout ->
                layout.addItemDecoration(SpaceTBDecoration())

                mAdapter = SlimAdapter.creator()
                    .register<DispatchPay>(R.layout.item_report_dispatch_pay) { jector, bean, index ->
                        jector.apply {
                            text(R.id.item_pay_barrel, bean.name)
                            text(R.id.item_pay_out, bean.quantity)
                            text(R.id.item_pay_price, bean.price.formatDecimal())
                            text(R.id.item_pay_memo, bean.memo1)
                            // 免单
                            text(R.id.item_pay_free, bean.free)
                            // 漏桶
                            text(R.id.item_pay_omit, bean.swap)
                            // 水票抵扣
                            text(R.id.item_pay_ticket, bean.exchange)
                            text(R.id.item_pay_amount, bean.exchangePrice.formatDecimal())
                            // 优惠券
                            text(R.id.item_pay_coupon, bean.coupon.formatDecimal())
                            // 小计
                            text(R.id.item_pay_total, bean.memo)

                            visibility(
                                R.id.item_pay_ticket_ll,
                                visibleValue { bean.exchange.intValue > 0 }
                            )

                            visibility(
                                R.id.item_pay_coupon_ll,
                                visibleValue { bean.coupon.doubleValue > 0 }
                            )

                            visibility(
                                R.id.item_pay_memo,
                                goneValue { bean.memo1.isNullOrEmpty() }
                            )

                            clicked(R.id.item_pay_edit) {
                                startActivityEx<ReportDispatchPayActivity>(
                                    "data" to bean,
                                    "index" to index
                                )
                            }
                        }
                    }
                    .attachTo(layout)
                    .addFooter(baseContext, R.layout.footer_report_pay) { _, view ->
                        mTotalView = view.find(R.id.pay_total)
                    }
            }
        }
    }

    override fun initListener() {
        mShipId = intent.getExtra("shipId")
        mOrderSn = intent.getExtra("orderSn")
        mShippingSn = intent.getExtra("shippingSn")

        mBinding.apply {
            btNext.oneClick {
                if (mList.isEmpty()) {
                    showToast("获取商品信息失败，请返回重试")
                    return@oneClick
                }

                getViewModel()
                    .dispatchSecond(
                        "sn" to mShippingSn,
                        "body" to Gson().toJson(mList)
                    )
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            goToDispatchThird(
                                "shipId" to mShipId,
                                "orderSn" to mOrderSn,
                                "shippingSn" to mShippingSn
                            )
                        }
                    )
            }
        }

        // 观察收款编辑
        LiveEventBus
            .get("dispatchSecond", DispatchPay::class.java)
            .observe(this) {
                mList[it.position] = it

                mTotalEvent.value = mList.size
                mAdapter.notifyDataSetChanged()
            }
    }

    /**
     * 收款列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .dispatchPay(mShippingSn)
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = { result ->
                    val obj = JSONObject(result)

                    val objItems = obj.optJSONArray("shippingItems") ?: JSONArray()
                    mList.clear()
                    mList.addItems(
                        JsonUtil.toList(
                            objItems.toString(),
                            DispatchPay::class.java
                        )
                    )
                    mTotalEvent.value = mList.size

                    mAdapter.setDataList(mList)
                }
            )
    }

    /**
     * 观察合计信息
     */
    private fun observeTotal() {
        mTotalEvent
            .observe(this) { value ->
                mTotalView.text = when {
                    value == 1 -> (mList[0] as DispatchPay).subPrice.formatDecimal()
                    value > 0 -> {
                        var totalMoney = 0.0
                        val totalHint = mList.map {
                            it as DispatchPay
                            totalMoney += it.subPrice.doubleValue
                            it.subPrice.doubleValue
                        }.joinToString(" + ")

                        "$totalHint = ${totalMoney.formatDecimal()}"
                    }
                    else -> "0.00"
                }
            }
    }

}